import {
	changeRouterUrl,
	deepClone,
	getUUid,
	getPageInfo
} from "./until"
import {
	onAppRoute
} from "./onAppRote"
/**路由的标识符key值 */
const routerKey = getUUid()
//原始路由参数
// interface TypeRouterParams { [key: string]: any }
// /**路由参数携带 */
// export interface TypePageDataItem { [key: string]: any, data: any, callBack: (alue: unknown) => void, backData: any, key: string }

/**全局路由数据缓存数据 */
const routerPageData = new Map()


/**设置路由值 @returns {url:新的路由地址 data:设置后的路由数据} */
function set(url, item, callBack = () => {}) {
	const routerData = changeRouterUrl(url, routerKey)
	const dataItem = {
		data: item,
		callBack,
		backData: null,
		key: routerData.key
	}
	routerPageData.set(routerData.key, dataItem)
	return {
		data: deepClone(routerPageData),
		url: routerData.url
	}
}

function getCurrentInstance() {
	const _pages = getCurrentPages()
	const _now = _pages[_pages.length - 1]
	return {
		router: {
			params: _now.options || null
		}
	}
}
/**获取路由数据 @returns TypePageDataItem */
function get() {
	const _params = getCurrentInstance().router?.params
	const TaroRouterParams = _params || {
		[routerKey]: "",
		data: null
	}
	return routerPageData.get(TaroRouterParams[routerKey])
}
/**设置页面返回携带的参数 */
function setBackData(data) {
	const _params = getCurrentInstance().router?.params
	const TaroRouterParams = _params || {
		[routerKey]: "",
		data: null
	}
	const item = routerPageData.get(TaroRouterParams[routerKey])
	if (item) {
		item["backData"] = data
	}
	return data
}
/**监听页面返回 */
function monitorPageBack(paged) {
	if (paged?.callBack instanceof Function) paged.callBack(paged.backData || null)
	onKeepDataClear()
}
/**动态清空路由中无用的数据 */
function onKeepDataClear() {
	setTimeout(() => {
		const keysListInRouterPageData = getKeyInMap(routerPageData)
		const routeInfo = getPageInfo()
		keysListInRouterPageData.map((v) => {
			let isInRoute = false
			routeInfo.list.map((value) => {
				if (v === value.routeID + "") isInRoute = true
			})
			if (!isInRoute) {
				routerPageData.delete(v)
			}
		})
	}, 0);
}
// //路由监听
onAppRoute(() => {
	const _pages = getCurrentPages()
	const _now = _pages[_pages.length - 1]
	const _pageData = get()
	const _fn = _now.onUnload
	_now.onUnload = function() {
		if (_fn instanceof Function) _fn(...arguments)
		monitorPageBack(_pageData)
	}
})
export default {
	data: routerPageData,
	set,
	get,
	setBackData,
	monitorPageBack,
}






function getKeyInMap(_map) {
	const _list = [],
		_keys = routerPageData.keys()
	for (const key of _keys) {
		_list.push(key)
	}
	return _list
}
